# -*- coding: utf-8 -*-
"""
Created on Thu May 11 15:33:28 2023

@author: ZHOU
"""
import time
import random
from decimal import Decimal

data_choice_1=[-5,-4,-4,-3,-3,-3,-2,-2,-2,-1,-1,-1,-1,0,0,0,0,1,1,1,1,2,2,2,3,3,3,4,4,5]

data_choice_2=[Decimal("-0.000009"),Decimal("-0.000006"),Decimal("-0.000006"),\
               Decimal("-0.000003"),Decimal("-0.000003"),Decimal("-0.000003"),\
               Decimal("-0.000001"),Decimal("0.000001"),Decimal("0"),\
               Decimal("0.000003"),Decimal("0.000003"),Decimal("0.000003"),\
               Decimal("0.000009"),Decimal("0.000006"),Decimal("0.000006")]

'''data keywords
心率 "heartrate"
踏频 "cadence"
距离 "distance"
功率 "power"
'''
def find_pole(gpx):
    south=-90
    north=90
    west=-180
    east=180
    location=[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]]
    for i in range(len(gpx)):
        if gpx[i].count('<trkpt'):
            s_list=gpx[i].split('"')
            lat=Decimal(s_list[1])
            lon=Decimal(s_list[3])
            if lat>south:  #最北
                south=lat
                location[0]=[lat,lon]
            if lat<north:  #最南
                north=lat
                location[1]=[lat,lon]
            if lon>west:  #最东
                west=lon
                location[2]=[lat,lon]
            if lon<east:  #最西
                east=lon
                location[3]=[lat,lon]
    return location

def change_location(gpx,lat_add,lon_add):
    gpx_list=[]
    s=''
    lat_add=Decimal(str(lat_add))
    lon_add=Decimal(str(lon_add))
    for i in range(len(gpx)):
        s=gpx[i]
        if gpx[i].count('<trkpt'):
            s_list=gpx[i].split('"')
            lat=Decimal(s_list[1])+lat_add
            lon=Decimal(s_list[3])+lon_add
            s=s_list[0]+'"'+str(lat)+'"'+s_list[2]+'"'+str(lon)+'"'+s_list[4]
        gpx_list.append(s)
    return gpx_list

def change_location_random(gpx):
    gpx_list=[]
    s=''
    data_choice=[]
    for i in data_choice_2:
        i=Decimal(str(i))
        data_choice.append(i)

    for i in range(len(gpx)):
        s=gpx[i]
        if gpx[i].count('<trkpt'):
            s_list=gpx[i].split('"')
            lat=Decimal(s_list[1])+random.choice(data_choice) 
            lon=Decimal(s_list[3])+random.choice(data_choice) 
            s=s_list[0]+'"'+str(lat)+'"'+s_list[2]+'"'+str(lon)+'"'+s_list[4]
        gpx_list.append(s)
    return gpx_list

def change_ele(gpx,coefficient,add):
    gpx_list=[]
    s=''
    for i in range(len(gpx)):
        s=gpx[i]
        try:
            el=str((gpx[i].split("<ele>")[1]).split("</ele>")[0])
            change_el=int(int(el)*coefficient+add)
            s=str(gpx[i].replace(el,str(change_el)))
        except:
            pass
        gpx_list.append(s)
    return gpx_list

def change_ele_climb(gpx,coefficient,add):
    gpx_list=[]
    s=''
    j=0
    for i in range(len(gpx)):
        s=gpx[i]
        try:
            el=str((gpx[i].split("<ele>")[1]).split("</ele>")[0])
            change_el=int(j*coefficient+add)
            j=j+1
            s=str(gpx[i].replace(el,str(change_el)))
        except:
            pass
        gpx_list.append(s)
    return gpx_list

def data_list_creat(n,avg,ran):
    data_list=[]
    data_list.append(avg)
    data_choice=data_choice_1.copy()
    min_data=avg-ran
    max_data=avg+ran
    for i in range(n-1):  
        num=data_list[i]+random.choice(data_choice) 
        if num < min_data:
            num=data_list[i]+1
        if num > max_data:
            num=data_list[i]-1
        data_list.append(num)            
        
    return data_list

def clean_data(gpx,keywords):
    gpx_list=[]
    s=''
    clean_flag=0
    for i in range(len(gpx)):
        s=gpx[i]   
        if clean_flag==0:
            if gpx[i].count("<"+keywords+">"):
                clean_flag=1
                s_list=gpx[i].split("<"+keywords+">")
                if gpx[i].count("</"+keywords+">"):
                    clean_flag=0                    
                    s2_list = s_list[1].split("</"+keywords+">")
                    s_list[1]=s2_list[1]
                s=s_list[0]+s_list[1]
        else:
            if gpx[i].count("</"+keywords+">"):
                clean_flag=0
                s_list=gpx[i].split("</"+keywords+">")
                s=s_list[1]
            else:
                s=''            
        gpx_list.append(s)
    return gpx_list

def make_time(gpx,coefficient,time_str):
    gpx_list=[]
    s=''
    first_time=time.mktime(time.strptime(time_str, "%Y-%m-%dT%H:%M:%SZ"))
    now_time=first_time
    flag=0
    for i in range(len(gpx)):
        s=gpx[i]
        if gpx[i].count('</time>') and flag==0:
            s='<time>'+time_str+'</time>\n'
            flag=1
        elif gpx[i].count('<trk>') and flag==0:
            s='<time>'+time_str+'</time>\n'+ gpx[i]
            flag=1
        elif flag==1:
            try:
                if gpx[i].count('</ele>'):
                    now_time=now_time+1*coefficient
                    change_time=time.strftime("%Y-%m-%dT%H:%M:%SZ",time.localtime(now_time))  
                    s_list=s.split("</ele>")
                    s=s_list[0]+'</ele>\n<time>'+change_time+'</time>'+s_list[1]
            except:
                pass
        gpx_list.append(s)
    return gpx_list

def make_data(gpx,avg,ran,keywords):
    gpx_list=[]
    data_list=[]
    num_list=[]
    s=''
    j=0
    distance=0
    for i in range(len(gpx)):
        try:
            if gpx[i].count('</time>'):
                j=j+1
                num_list.append(i)
        except:
            pass

    data_list=data_list_creat(j,avg,ran)
    j=0    
    for i in range(len(gpx)):
        s=gpx[i]   
        try:
            if i==num_list[j]: 
                s_list=s.split("</time>")                
                if keywords == "distance":
                    distance=distance+data_list[j]
                    s=s_list[0]+"</time>\n<extensions><"+keywords+">"+str(distance)+"</"+keywords+"></extensions>"+s_list[1]
                else:
                    s=s_list[0]+"</time>\n<extensions><"+keywords+">"+str(data_list[j])+"</"+keywords+"></extensions>"+s_list[1]
                j=j+1
        except:
            pass
        gpx_list.append(s)
    return gpx_list

def change_data(gpx,coefficient,keywords):
    gpx_list=[]
    s=''
    for i in range(len(gpx)):
        s=gpx[i]
        try:
            heart=str((gpx[i].split("<"+keywords+">")[1]).split("</"+keywords+">")[0])
            change=int(int(heart)*coefficient)                
            s=str(gpx[i].replace(heart,str(change)))
        except:
            pass
        gpx_list.append(s)
    return gpx_list

def change_time(gpx,coefficient,time_add):
    gpx_list=[]
    s=''
    first_time=0
    for i in range(len(gpx)):
        s=gpx[i]
        try:
            ti=str((gpx[i].split("<time>")[1]).split("</time>")[0])
            now_time = time.mktime(time.strptime(ti, "%Y-%m-%dT%H:%M:%SZ"))
            if first_time==0:
                first_time=now_time
                change_time=now_time+time_add
            else:
                change_time=((now_time-first_time)*coefficient)+first_time+time_add
            change_time=time.strftime("%Y-%m-%dT%H:%M:%SZ",time.localtime(change_time))  
            s=str(gpx[i].replace(ti,str(change_time)))
        except:
            pass
        gpx_list.append(s)
    return gpx_list

def copy_gpx(gpx,n,random_flag):
    gpx_list=[]
    gpx_trkpt_list=[]
    gpx_trkpt_list_change=[]
    s=''
    
    first_time=0
    last_time=0
    single_time=0
    
    flag=0
    for i in range(len(gpx)):
        s=gpx[i]
        try:
            ti=str((gpx[i].split("<time>")[1]).split("</time>")[0])
            now_time = time.mktime(time.strptime(ti, "%Y-%m-%dT%H:%M:%SZ"))
            if first_time==0:
                first_time=now_time
            else:
                last_time=now_time
        except:
            pass
        if flag==0:
            gpx_list.append(s)
            if gpx[i].count('<trkseg>'):
                flag=1
        else:
            if gpx[i].count('</trkseg>'):
                s=gpx[i].split("</trkseg>")[0]
                gpx_trkpt_list.append(s)
                break
            else:
                gpx_trkpt_list.append(s)
    
    single_time=last_time-first_time
    
    for i in range(n):
        gpx_trkpt_list_change=change_time(gpx_trkpt_list,1,single_time*n+1)
        if random_flag==1:
            gpx_trkpt_list_change=change_location_random(gpx_trkpt_list_change)
        gpx_list=gpx_list+gpx_trkpt_list_change
    gpx_list.append("\n</trkseg>\n</trk>\n</gpx>\n")
    
    return gpx_list

    
def save_gpx(gpx,path):
    try:
        f=open(path, 'w', encoding="utf-8")
    except:
        f=open(path, 'a', encoding="utf-8")
    for i in gpx:
        f.write(i)
    f.close()
    

if __name__ == '__main__':
    path="./jzgc/jzgc_text_run.gpx"
    
    f=open(path, 'r', encoding="utf-8")
    gpx_lines=f.readlines()
    f.close()    
    
#    gpx=change_location(gpx_lines,-0.153443,-2.091354)
#    gpx=make_time(gpx_lines,1,"2023-05-23T23:34:17Z")
    gpx=make_data(gpx_lines,120,20,"heartrate")
#    gpx=make_data(gpx,250,50,"power")
    gpx=make_data(gpx,100,10,"cadence")
#    gpx=change_time(gpx_lines,1,-1361651)
#    gpx=change_location_random(gpx)

    save_gpx(gpx,path)
    
